import JWT from 'jsonwebtoken'
import { Result } from '~~/lib/helper/result'
const whiteList = ['/', '/api/auth/login', '/api/auth/register']
export default defineEventHandler((event) => {
  // 部分请求跳过 token 校验
  const requestUrl = event.node.req.url || ''
  if (whiteList.includes(requestUrl)) return
  // 获取 token
  let token = getHeader(event, 'Authorization')
  if (token) {
    // 处理 token
    token = token.replace('Bearer ', '')
    const secrect = 'jwt-secrect'
    try {
      // 验证 token
      const decoded = JWT.verify(token, secrect)
      console.log('decoded', decoded)
      // 传递给上下文
      event.context.auth = (decoded as any).id
    } catch (error) {
      console.log('登录失效')
      return Result.Error('登录失效，请重新登录！', 401)
    }
  } else {
    return Result.Error('登录失效，请重新登录！', 401)
  }
})
